<template>
  <div class="manage">
    <el-drawer
        title="编辑工单"
        :visible.sync="drawer"
        size="40%"
        style="text-align: center"
        :before-close="handleClose"
        :destroy-on-close="true"
    >
      <div class="drawerContainer">
        <el-form  size="mini" ref="form" :rules="rules" :inline="true" :model="form" label-width="200px" label-position="right">
          <el-form-item label="隐患类型" prop="type">
            <el-select style="width: 220px" v-model="form.type" placeholder="请选择隐患类型" @change="changeType">
              <el-option v-for="item in dangerTypeList"
                         :key="item"
                         :label="item"
                         :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="隐患领域" prop="area">
            <el-select style="width: 220px" v-model="form.area" placeholder="请选择隐患领域" @change="changeArea">
              <el-option v-for="item in dangerAreaList"
                         :key="item"
                         :label="item"
                         :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="隐患标题" prop="task_title">
            <el-input @input="getTitle"  style="width: 220px" type="text" show-word-limit placeholder="请输入标题" clearable  maxlength="100" v-model="form.task_title"></el-input>
          </el-form-item>
          <el-form-item label="检查时间" prop="task_inspection_time">
            <el-date-picker
                v-model="form.task_inspection_time"
                value-format="yyyy-MM-dd"
                align="right"
                type="date"
                placeholder="请输入检查时间"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="规定整改完成时间" prop="task_anticipate_time">
            <el-date-picker
                v-model="form.task_anticipate_time"
                value-format="yyyy-MM-dd"
                align="right"
                type="date"
                placeholder="请输入规定整改完成时间"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="风险隐患等级" prop="task_level">
            <el-select style="width: 220px" v-model="form.task_level" placeholder="请选择风险隐患等级" @change="getLevel">
              <el-option v-for="item in levelList"
                         :key="item.id"
                         :label="item.label"
                         :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="场所或施工项目名称" prop="task_name">
            <el-input @input="getName" style="width: 220px" type="text" show-word-limit placeholder="请输入场所或施工项目名称" clearable  maxlength="100" v-model="form.task_name"></el-input>
          </el-form-item>
          <el-form-item label="问题及隐患详情" prop="task_content">
            <el-input @input="getContent"  :rows="5" type="textarea" style="width: 220px" show-word-limit v-model="form.task_content" clearable placeholder="请输入问题及隐患详情" ></el-input>
          </el-form-item>
          <el-form-item label="责任部门" prop="task_dept">
            <el-select style="width: 220px" v-model="form.task_dept" placeholder="请选择部门" @change="getDept">
              <el-option v-for="item in deptList"
                         :key="item"
                         :label="item"
                         :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="整改照片" prop="images_before">
            <el-upload
                v-model="imgs"
                action=""
                ref="uploadImg1"
                list-type="picture-card"
                v-loading="uploading"
                :auto-upload="false"
                :file-list="fileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="handleFileChange"
                :before-remove="beforeRemove"
                :class="{disabled:uploadDisabled}"
                :limit="15"
                :on-exceed="handleExceed"
            >
              <span :class="{disabled:uploadDisabled}">
                <i  class="el-icon-plus"></i>
              </span>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，</div>
              <div slot="tip" class="el-upload__tip">且单张不超过2MB</div>
            </el-upload>
            <el-dialog :visible.sync="dialogImgVisible">
              <img width="100%" :src="dialogImageUrl" alt="图片未找到">
            </el-dialog>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-left: 20%">
        <el-button  @click="cancel" size="mini">取消</el-button>
        <el-button style="margin-left: 3em"  type="primary" @click="submit" size="mini">提交</el-button>
      </div>
    </el-drawer>
    <div class="manage-header">
      <!--          form搜索区域-->
      <el-form :inline="true" :model="userForm" size="mini">
        <el-form-item label="责任部门：" prop="deptname">
          <el-select v-model="userForm.deptname" placeholder="请选择责任部门">
            <el-option label="所有部门" value=""></el-option>
            <el-option
                v-for="item in deptList"
                :key="item"
                :label="item"
                :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onSubmit" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table">
      <el-table
          stripe
          height="90%"
          border
          size="mini"
          :data="tableData"
          style="width: 100%">
        <el-table-column
            fixed
            prop="id"
            label="工单编号"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="task_title"
            label="标题"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_dept__safeer__name"
            label="安全员"
            align="center"
        >
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.task_dept__safeer__name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="task_dept__depthearder__name"
            label="负责人"
            align="center"
        >
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" type="success">{{ scope.row.task_dept__depthearder__name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="task_name"
            label="场所或施工项目名称"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_content"
            label="问题及隐患详情"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_inspection_time"
            label="检查时间"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_anticipate_time"
            label="规定整改完成时间"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_type__type"
            label="隐患类型"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="task_type__area"
            label="隐患领域"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="task_dept__deptname"
            label="责任部门"
            align="center"
            :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            align="center"
        >
          <template>
            <el-tag type="warning">待发起</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="task_level"
            label="风险等级"
            align="center"
        >
          <template slot-scope="scope">
            <span :style="{ color: scope.row.task_level ==='一般' ? 'green' :'red'}"
            >
              {{scope.row.task_level}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="200px"
        >
          <template slot-scope="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="edit(scope.row)">
              编辑
            </el-button>
            <el-button type="info"
                       icon="el-icon-s-tools"
                       size="mini"
                       style="background-color: red"
                       @click="release(scope.row.id)">
              发起
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="paginations.current"
            :page-sizes="[5 ,10, 20, 50, 100]"
            :page-size="paginations.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginations.total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {dangerType,dangerArea} from '@/api/dangertypes'
import {deptInfo} from "@/api/dept";
import {handleTask, taskInfo, taskList, updateTask} from "@/api/task";
export default {
  name: "WorkOrderAudit",
  data(){
    return{
      imgs:'',
      index:'',
      drawer:false,
      uploading:false,
      uploadDisabled:false,
      dialogImgVisible:false,
      dialogImageUrl:'',
      fileList:[],
      dangerTypeList:[],
      dangerAreaList:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      form: {
        task_id:'',
        type: '',
        area: '',
        task_title:'',
        images_before:[],
        task_anticipate_time:'',
        task_level:'',
        task_content:'',
        task_name:'',
        task_inspection_time:'',
        task_type:'',
        task_dept:'',
      },
      dangerArray:[],
      deptList:[],
      dialogVisible: false,
      levelList:[
        {
          id:1,
          value:'重大',
          label:'重大'
        },
        {
          id:2,
          value:'一般',
          label:'一般'
        }
      ],
      statusLists:[
        {
          label:'有效',
          value:1
        },
        {
          label:'无效',
          value: 0
        },
        {
          label:'全部',
          value: ''
        }
      ],
      rules: {
        type: [
          {
            required: true,
            message: '请输入隐患类型'
          }
        ],
        area: [
          {
            required: true,
            message: '请输入隐患领域'
          }
        ]
      },
      typelists:[],
      tableData: [],
      paginations: {
        current: 1, //当前页
        pageSize: 10, //一页显示多少条
        total: 0 //数据总数
      },
      userForm: {
        deptname:''
      }
    }
  },
  mounted() {
    this.created();
  },
  methods: {
    created() {
      let _this = this;
      deptInfo({}).then(resp=>{
        if(resp.code===1){
          let params = {
            page_number: 1,
            page_size:resp.total_count,
            status: true
          }
          deptInfo(params).then(res=>{
            let temp = res.data
            for(let i = 0;i<temp.length;i++){
              _this.deptList = [..._this.deptList,temp[i].deptname]
            }
            console.log(_this.deptList)
          })

        }
      })
      dangerType({}).then(res=>{
        if(res.code === 1){
          _this.dangerTypeList = res.data
        }
      })
      this.getList()
    },
    //弹窗关闭的时候
    handleClose (done) {
      this.$confirm('确定关闭吗？')
          .then(()=> {
            this.$refs.form.resetFields()
            this.form = {}
            this.form.images_before=[]
            done();
          })
          .catch(()=> {});
    },
    getDept(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    getTitle(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    getName(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    getContent(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    cancel () {
      this.$refs.form.resetFields()
      this.fileList=[]
      this.form = {}
      this.form.images_before = []
    },
    submit(){
      this.$refs.form.validate((valid) => {
        if(valid) {
          delete this.form.type
          delete this.form.area
          console.log(this.form)
          updateTask(this.form).then(res=>{
            if(res.code === 1){
              this.$message.success(res.message)
              this.cancel()
              this.drawer = false
              this.getList()
            }
          })
        }
      })
    },
    //分页方法
    handleCurrentChange(val) {
      this.paginations.current = val
      this.getList();
    },
    handleSizeChange(val) {
      this.paginations.pageSize = val
      this.getList();
    },
    //获取的列表数据
    getList () {
      //获取的列表数据
        let params = {
          deptname:this.userForm.deptname,
          status:[1],
          page_number:this.paginations.current,
          page_size:this.paginations.pageSize
        }
        taskList(params).then(resp => {
          if (resp.code === 1) {
            console.log(resp.data)
            this.tableData = resp.data
            this.paginations.total = resp.total_count
          }
        })

    },
    //列表的查询
    onSubmit () {
      this.getList()
    },
    edit(row){
      this.drawer = true
      this.form.task_id = row.id
      this.form.area = row.task_type__area
      this.form.type = row.task_type__type
      this.form.task_content = row.task_content
      this.form.task_dept = row.task_dept__deptname
      this.$set(this.form,'task_anticipate_time',row.task_anticipate_time)
      this.$set(this.form,'task_inspection_time',row.task_inspection_time)
      this.form.task_level = row.task_level
      this.form.task_name = row.task_name
      this.form.task_title = row.task_title
      this.form.task_type = row.task_type
      taskInfo({task_id:row.id}).then(res=>{
        if(res.code===1){
          this.imgs = res.image_before
          this.fileList = this.imgs.map(t=>{
            var obj = {}
            obj.url = 'http://134.68.156.116:28881/yaq/api/media/'+t.image
            return obj
          })
          for (let i =0;i<this.imgs.length;i++){
            this.form.images_before = [...this.form.images_before,this.imgs[i].image_base64]
          }
          // let that = this
          // this.imgs.forEach(function (item){
          //   that.form.images_before = [...that.form.images_before,item.image_base64]
          // })
          console.log(this.fileList)
          console.log(this.form.images_before)
        }
      })

    },
    release(id){
      let params = {
        link:1,
        task_id:id
      }
      handleTask(params).then(res=>{
        if(res.code===1){
          this.$message.success(res.message)
          this.getList()
        }
      })
    },
    changeType(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      this.dangerArray = []
      this.dangerAreaList = []
      let params = {
        type:this.form.type,
        area:'',
        status:1
      }
      dangerArea(params).then(res=>{
        if(res.code === 1){
          let paramsArea= {
            type: this.form.type,
            area: '',
            status: 1,
            page_number:1,
            page_size:res.total_count
          }
          dangerArea(paramsArea).then(resp=>{
            this.dangerArray = resp.data
            for(let i = 0;i<this.dangerArray.length;i++){
              this.dangerAreaList = [...this.dangerAreaList,this.dangerArray[i].area]
            }
          })
        }
      })
    },
    changeArea(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      this.form.task_type = ''
      let dangerObject = this.dangerArray.filter(ele=>((ele.type === this.form.type)&&(ele.area === this.form.area)))
      console.log(dangerObject)
      this.form.task_type = dangerObject[0].id
      console.log(this.form.task_type)
    },
    handleFileChange(file,fileList){
      this.uploadDisabled=(fileList.length>=15)
      this.fileList = fileList
      console.log(file,fileList)
      console.log(this.fileList)
      console.log('imgs',this.imgs)
      const imgType = file.raw.type === 'image/jpeg'|| file.raw.type === 'image/png'
      const isLt2MB = file.size / 1024 / 1024 < 2;
      if (!imgType) {
        this.$message.error("上传图片只能是 JPG和png 格式!");
        this.uploadDisabled=(fileList.length>=15)
        console.log(fileList)
        return false
      }
      if(!file.raw){
        this.$message.error("选择图片错误！")
      }
      if (!isLt2MB) {
        this.uploading=true
        this.$message.success("图片大小超过2MB，正在压缩中...");
        setTimeout(() => {
          //代码
          this.uploading=false
        }, 2000);
        let that = this;
        let reader = new FileReader();
        // 将图片将转成 base64 格式
        reader.readAsDataURL(file.raw);
        reader.onloadend = function () {
          let result = this.result;
          console.log(result)
          let img = new Image();
          img.src = result;
          // compressImg.src = file.url;
          console.log(img.src)
          img.onload = function (){
            let maxWidth = 800;
            let maxHeight = 800;
            let originWidth = img.width; //图片原始宽
            let originHeight = img.height; //图片原始高
            // console.log(originWidth)
            // console.log(originHeight)
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d')
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
              }
            }
            canvas.width = targetWidth
            canvas.height = targetHeight
            // 图片压缩
            ctx.drawImage(img, 0, 0, targetWidth, targetHeight)
            // canvas对图片进行缩放 0.3是我定义的图片质量，
            let base64 = canvas.toDataURL(file.raw.type, 0.3);
            console.log(base64)
            //将base64转换为file流
            let Compressfile= that.convertBase64UrlToFile({
              dataURL: base64,
              type: file.raw.type,
              contentName: file.name
            })
            console.log('压缩后', Compressfile)
            file = {
              id: "compress",//标记图片的唯一性，可按自己方式定义
              url:Compressfile.path,
              file: Compressfile
            };
            setTimeout(function(){
              that.$message.success('已压缩至2MB以下')
            },2000)
            that.form.images_before=[...that.form.images_before,base64]
            console.log(result.length) //result是返回图片base64格式
            console.log(that.form.images_before.length)
            console.log(img.width)
            console.log(img.height)
            console.log(Compressfile)
            console.log(file,fileList)
            console.log(that.form.images_before)
            console.log(that.form.images_before[0])
            console.log(that.form.images_before[1])
            console.log(that.form.images_before[2])
            console.log(that.form.images_before[3])
            console.log(that.form.images_before[4])
            console.log(that.form.images_before[5])
          }
        }
      } else {
        //这里写直接上传 转base64
        const self = this;
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function (e) {
          let img_base64 = e.target.result;
          self.form.images_before = [...self.form.images_before,img_base64]
          console.log(self.form.images_before)
        }
      }
    },
    convertBase64UrlToFile(base64) {
      let urlData = base64.dataURL
      let type = base64.type
      let contentName = base64.contentName
      let bytes = null
      if (urlData.split(',').length > 1) { //是否带前缀
        bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
      } else {
        bytes = window.atob(urlData)
      }
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length)
      let ia = new Uint8Array(ab)
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      let result = new Blob([ab], {
        type: type,
      })
      let result1 = new File([result], contentName, {
        type: type
      })
      result1.path = window.URL.createObjectURL(result)
      return result1
    },
    handleExceed() {
      this.$message.warning(`只能上传十五张图片`);
    },
    beforeRemove(file,fileList) {
      this.index = fileList.indexOf(file)
      console.log('index',this.index)
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload(file){
      console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.uploadDisabled=(fileList.length>=15)
      this.form.images_before.splice(this.index,1)
      console.log(this.form.images_before)
    },
    handlePreview(file) {
      console.log(file.size);
      // window.open(file.url)
      this.dialogImageUrl = file.url;
      this.dialogImgVisible = true;
      this.uploadDisabled = true
    },
    getLevel(){
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.manage{
  height: 100%;
  .drawerContainer{
    text-align: center;
    margin-right: 10%;
    color: #fff;
    padding: 10px;
    font-size: 25px;
    .el-upload__tip{
      color: orangered;
    }
  }
  .manage-header{
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 1px dotted lightgrey;
  }
  .common-table{
    margin-top: 20px;
    position: relative;
    height: 90%;
    .pager{
      position: absolute;
      bottom: 0;
      right: 20px;
    }
  }
}
</style>
